sap.ui.define([
		"./BaseController",
		"./ItemDetailDialog",
		"./SendbackDialog",
		"./ForwardDialog",
		"sap/ui/model/json/JSONModel",
		"sap/m/UploadCollectionParameter",
		"sap/m/MessageToast",
		"sap/m/upload/Uploader",
		"../model/formatter",
		"sap/m/Dialog",
		"sap/m/Text",
		"sap/m/Input",
		"sap/m/TextArea",
		"sap/m/Button",
		"sap/m/Label",
		"sap/ui/layout/VerticalLayout",
		"sap/m/library"
	],
	function(BaseController, ItemDetailDialog, SendbackDialog, ForwardDialog, JSONModel, UploadCollectionParameter,
		MessageToast, Uploader,
		formatter, Dialog, Text, Input, TextArea, Button, Label, VerticalLayout, mobileLibrary) {
		"use strict";
		// shortcut for sap.m.URLHelper
		//  var URLHelper = mobileLibrary.URLHelper;
		// shortcut for sap.m.ButtonType
		var ButtonType = mobileLibrary.ButtonType;
		// shortcut for sap.m.DialogType
		var DialogType = mobileLibrary.DialogType;
		return BaseController.extend("com.wp.SWIFTSAP.controller.Detail", {

			formatter: formatter,
			/* =========================================================== */
			/* lifecycle methods                                           */
			/* =========================================================== */
			onInit: function() {
				// Model used to manipulate control states. The chosen values make sure,
				// detail page is busy indication immediately so there is no break in
				// between the busy indication for loading the view's meta data
				var oViewModel = new JSONModel({
					busy: false,
					delay: 0,
					lineItemTableDelay: 0,
					lineItemListTitle: this.getResourceBundle().getText("detailLineItemTableHeading"),
					historyItemListTitle: this.getResourceBundle().getText("historyLineItemTableHeading"),
					headjson: "",
					itemhjson: "",
					itemrjson: "",
					attachjson: "",
					historyjson: "",
					itemDetailJSON: "",
					sendbackjson: "",
					forwardUser: "",
					headerNoteLable: "",
					headerNoteText: "",
				});

				//Attach related start----->
				// Sets the text to the label
				this.byId("uploadCollection").addEventDelegate({
					onBeforeRendering: function() {
						this.byId("attachmentTitle").setText(this.getAttachmentTitleText());
					}.bind(this)
				});

				this._PDFViewer = null;
				this.vRequestid = null;
				this.vApplevel = null;
				this.vAppid = null;
				//Attach related end-----<

				this.getRouter().getRoute("inboxDetail").attachPatternMatched(this._onRequestMatched, this);
				this.setModel(oViewModel, "detailView");
				this.getOwnerComponent().getModel().metadataLoaded().then(this._onMetadataLoaded.bind(this));
			},

			productItemFactory: function(sId, oContext) {
				var oUIControl = [];
				var sObj = oContext.getObject();
				for (var i in sObj) { //遍历所有属性
					oUIControl.push(new sap.m.Text({
						text: sObj[i]
					}));
				}

				var oView = this.getView();
				var oDialog = new ItemDetailDialog(oView);

				var onPressToItemDetail = function(oEvent) {
					//var test = oEvent.oSource.getBindingContext();
					//实际是获取View
					//获取屏幕点击的ObjectListItem 元素
					var oItem = oEvent.getSource();
					// var msg = oItem.getBindingContext("invoice").getPath();
					// alert(msg); /Invoices/2  下面substr(1)是为了去掉开始的'/'
					var itemHData = oItem.getModel("detailView").getProperty("/itemhjson");
					var itemRData = oItem.getBindingContext("detailView").getObject();
					//合并行项目详细信息
					var itemDetailData = itemHData.map(function(item) {
						var vField = item.FIELD;
						//拼接的字段替换
						if (vField.indexOf("&")) {
							vField = vField.replace(/\&/g, "_");
						}
						for (var attr in itemRData) {
							if (attr === vField) {
								item.VALUE = itemRData[attr];
								break;
							}
						}
						return item;
					});
					oItem.getModel("detailView").setProperty("/itemDetailJSON", itemDetailData);
					oDialog.open(oView);
				};

				return new sap.m.ColumnListItem({
					cells: oUIControl,
					type: "Active",
					press: onPressToItemDetail
				});
			},

			_processRequest: function(oBtn, sAction, oThis) {
				var oView = oThis.getView();
				var oModel = oView.getModel();
				var Requestid = oThis.vRequestid; //oThis.getView().byId("requestid").getText();
				var Approverid = oThis.getOwnerComponent().getModel("user").getProperty("/Userid");
				var Language = oThis.getOwnerComponent().getModel("user").getProperty("/Language");
				var Comments = oView.byId("comments").getValue();
				var sPath = "/RequestSet('" + Requestid + "')/Applevel";
				var Applevel = oThis.getModel().getProperty(sPath);

				sPath = "/RequestSet('" + Requestid + "')/Appid";
				oThis.vAppid = oThis.getModel().getProperty(sPath);
				oThis.vApplevel = Applevel;

				if (sAction === "FORWARD") {
					var forwardDialog = new ForwardDialog(oView, oBtn, oThis);
					forwardDialog.open(oView, oBtn, oThis);
					return;
				}

				if (sAction === "SENDBACK") {
					var sendbackDialog = new SendbackDialog(oView, oBtn, oThis);
					sendbackDialog.open(oView, oBtn, oThis);
					return;
				}

				var fSuccessCallback = function() {
					oThis.onCloseDetailPress();
				};

				oModel.callFunction(
					"/ProcessRequest", {
						method: "POST",
						urlParameters: {
							Requestid: Requestid,
							Approverid: Approverid,
							Applevel: Applevel,
							Language: Language,
							Sendbacklevel: "",
							Action: sAction,
							Comments: Comments,
							Forwardapprovers: ""
						},
						success: function(oData) {
							oBtn.setEnabled(true);
							if (oData.Type === "S") {
								oThis.showSuccessMessage(oThis.getResourceBundle().getText("processRequestSuccess"), fSuccessCallback);
							} else {
								oThis.showErrorMessage(oThis.getResourceBundle().getText("processRequestFail", [oData.Message]));
							}
						},
						error: function(oError) {
							oBtn.setEnabled(true);
							oThis.showErrorMessage(oError.responseText);
						}
					});
			},

			/* =========================================================== */
			/* begin: internal methods                                     */
			/* =========================================================== */

			/**
			 * Binds the view to the object path and expands the aggregated line items.
			 * @function
			 * @param {sap.ui.base.Event} oEvent pattern match event in route 'object'
			 * @private
			 */
			_onRequestMatched: function(oEvent) {
				var sRequestid = oEvent.getParameter("arguments").Requestid;
				this.vRequestid = sRequestid;

				var oDetailPage = this.getView().byId("detailPage");
				var oViewModel = this.getModel("detailView");
				var oItemTable = this.getView().byId("lineItemsList");
				var oUploadCollection = this.getView().byId("uploadCollection");

				var sPath = "/RequestSet('" + sRequestid + "')";
				var oRequest = this.getModel().getProperty(sPath);
				if (oRequest) {
					var vFlagUpload = oRequest.Flag_upload;
				} else { //浏览器直接刷新过来侧直接返回
					//	return;
				}

				this.getView().byId("comments").setValue("");
				this.getModel("appView").setProperty("/layout", "TwoColumnsMidExpanded");
				//this.byId("downloadButton").setEnabled(false);
				//this.byId("versionButton").setEnabled(false);
				oItemTable.setVisible(true);
				oUploadCollection.setVisible(true);

				var fRequestid = new sap.ui.model.Filter({
					path: "Requestid",
					operator: sap.ui.model.FilterOperator.EQ,
					value1: sRequestid
				});
				var oFilter = [];
				oFilter.push(fRequestid);

				var oThis = this;
				var onAction = function(oEvt) {
					var Comments = oThis.getView().byId("comments").getValue();
					var oButton = oEvt.getSource();
					var sId = oButton.getId();
					if (sId === "REJECT" && Comments === "") {
						if (!this.oCommDialog) {
							this.oCommDialog = new Dialog({
								title: oThis.getResourceBundle().getText("rejectDialogTitle"),
								draggable: true,
								type: DialogType.Message,
								content: [
									new VerticalLayout({
										width: "100%",
										content: [
											new Text({
												text: oThis.getResourceBundle().getText("rejectDialogText")
											}).addStyleClass("sapUiTinyMarginBottom"),
											new Label({
												text: oThis.getResourceBundle().getText("rejectDialogLable"),
												required: true,
												labelFor: "rejectionNote"
											}),
											new TextArea("rejectionNote", {
												width: "100%",
												liveChange: function(oChangeEvent) {
													var sTextAreaValue = oChangeEvent.getSource().getValue();
													this.oCommDialog.getBeginButton().setEnabled(sTextAreaValue.length > 0);
												}.bind(this),
												placeholder: oThis.getResourceBundle().getText("rejectDialogPlaceholder")
											})
										]
									})

								],
								beginButton: new Button({
									type: ButtonType.Emphasized,
									enabled: false,
									text: oThis.getResourceBundle().getText("rejectDialogBeginButtonText"),
									press: function() {
										oThis.getView().byId("comments").setValue(sap.ui.getCore().byId("rejectionNote").getValue());
										this.oCommDialog.close();
										this.oCommDialog.destroy();
										oThis._processRequest(oButton, sId, oThis);

									}.bind(this)
								}),
								endButton: new Button({
									text: oThis.getResourceBundle().getText("rejectDialogEndButtonText"),
									press: function() {
										this.oCommDialog.close();
									}.bind(this)
								})
							});
						}
						this.oCommDialog.open();
					} else {
						oThis._processRequest(oEvt.getSource(), oEvt.getSource().getId(), oThis);
					}

				};

				this.getModel().metadataLoaded().then(function() {
					//If Request is null, from URL direct
					/*          if (!oRequest) {
					            this.getModel().read(sPath, {
					              success: function(oData) {
					                var oViewModelTmp = new JSONModel(oData);
					                this.getView().setModel(oViewModelTmp);
					              }.bind(this),
					              error: function(oData) {
					                this.getView().setModel("");
					                this.showErrorMessage(oData.message);
					              }.bind(this)
					            });
					          }*/

					//读取request信息
					var sObjectPath = this.getModel().createKey("RequestSet", {
						Requestid: sRequestid
					});
					this._bindView("/" + sObjectPath); //RequestSet(Requestid="0000003")

					var vLanguage = this.getOwnerComponent().getModel("user").getProperty("/Language");
					//读取request 行项目信息
					var sObjectPath01 = this.getModel().createKey("/ReqjsonSet", {
						Requestid: sRequestid
					});

					oDetailPage.destroyFooterCustomActions();
					oDetailPage.destroyNegativeAction();
					oDetailPage.destroyPositiveAction();

					this.getModel().attachRequestSent(function() {
						sap.ui.core.BusyIndicator.show();
					});

					this.getModel().attachRequestCompleted(function() {
						sap.ui.core.BusyIndicator.hide();
					});

					this.getModel().read(sObjectPath01, {
						success: function(oData) {
							var oHeadjson = oData.Headjson,
								oItemhjson = oData.Itemhjson,
								oItemrjson = oData.Itemrjson,
								oAttachjson = oData.Attachjson,
								oActionjson = oData.Actionjson;
							if (oHeadjson !== "") {
								oHeadjson = JSON.parse(oHeadjson);
								oHeadjson.shift();
								//多语言支持
								for (var i in oHeadjson) {
									if (vLanguage.indexOf("zh") !== -1) {
										oHeadjson[i].NAME3 = oHeadjson[i].NAME1;
									} else if (vLanguage.indexOf("en") !== -1) {
										oHeadjson[i].NAME3 = oHeadjson[i].NAME2;
									}
									if (oHeadjson[i].FIELD === "ZTETXH") {
										//replace all "|" with "\t\n"
										if (oHeadjson[i].VALUE) {
											oHeadjson[i].VALUE = oHeadjson[i].VALUE.replace(/\|/g, "\t\n");
										}

										this.getView().getModel("detailView").setProperty("/headerNoteLable", oHeadjson[i].NAME3);
										this.getView().getModel("detailView").setProperty("/headerNoteText", oHeadjson[i].VALUE);
										oHeadjson[i]["VISIBLE"] = false;
									} else {
										oHeadjson[i]["VISIBLE"] = true;
									}
									if (oHeadjson[i].FIELD === "LBLNI" || oHeadjson[i].FIELD === "EBELN" || oHeadjson[i].FIELD === "LIFNR") {
										oHeadjson[i]["ATTACTIVE"] = true;
									} else {
										oHeadjson[i]["ATTACTIVE"] = false;
									}

								}
							}
							if (oItemrjson !== "") {
								oItemrjson = JSON.parse(oItemrjson);
							} else {
								oItemTable.setVisible(false);
							}
							if (oItemhjson !== "") {
								oItemhjson = JSON.parse(oItemhjson);
								for (var j in oItemhjson) {
									//多语言支持
									if (vLanguage.indexOf("zh") !== -1) {
										oItemhjson[j].NAME3 = oItemhjson[j].NAME1;
									} else if (vLanguage.indexOf("en") !== -1) {
										oItemhjson[j].NAME3 = oItemhjson[j].NAME2;
									}
									oItemhjson[j].VISIBLE = true;
									if (oItemrjson.length > 0) {
										var oItemRow0 = oItemrjson[0];
										if (oItemRow0[oItemhjson[j]["FIELD"]] === "") {
											oItemhjson[j].VISIBLE = false;
										}
									}
									if (oItemhjson[j].FIELD === "EXTROW" || oItemhjson[j].FIELD === "MEINS") {
										oItemhjson[j].WITH = "3rem";
									} else if (oItemhjson[j].FIELD === "MENGE" || oItemhjson[j].FIELD === "TBTWR" || oItemhjson[j].FIELD === "BRTWR") {
										oItemhjson[j].WITH = "5rem";
									} else if (oItemhjson[j].FIELD === "KTEXT1") {
										oItemhjson[j].WITH = "20%";
									} else if (oItemhjson[j].FIELD === "AUFNR" || oItemhjson[j].FIELD === "KOSTL" || oItemhjson[j].FIELD === "SAKTO") {
										oItemhjson[j].WITH = "6rem";
									} else if (oItemhjson[j].FIELD === "TXT20" || oItemhjson[j].FIELD === "KTEXT2" || oItemhjson[j].FIELD === "KTEXT") {
										oItemhjson[j].WITH = "12%";
									}

								}
							}

							if (oAttachjson !== "") {
								oAttachjson = JSON.parse(oAttachjson);
							} else { //不可上传附件的情况下，隐藏附件控件
								if (vFlagUpload === "") {
									oUploadCollection.setVisible(false);
								}
							}

							//动态添加按钮
							if (oActionjson !== "") {
								oActionjson = JSON.parse(oActionjson);
								var oButton = null;
								var vBtnText = "";
								for (var k in oActionjson) {
									if (vLanguage.indexOf("zh") !== -1) {
										vBtnText = oActionjson[k].DESC1;
									} else if (vLanguage.indexOf("en") !== -1) {
										vBtnText = oActionjson[k].DESC2;
									} else {
										vBtnText = oActionjson[k].DESC3;
									}

									//oButton = new sap.m.Button({
									//      id: oActionjson[k].ACTION,
									//      text: vBtnText,
									//      press: onAction
									//    });
									//oDetailPage.addFooterCustomAction(oButton);

									switch (oActionjson[k].ACTION) {
										case "APPROVE":
											oButton = new sap.f.semantic.PositiveAction({
												id: oActionjson[k].ACTION,
												text: vBtnText,
												press: onAction
											});
											oDetailPage.setPositiveAction(oButton);
											break;
										case "REJECT":
											oButton = new sap.f.semantic.NegativeAction({
												id: oActionjson[k].ACTION,
												text: vBtnText,
												press: onAction
											});
											oDetailPage.setNegativeAction(oButton);
											break;
										default:
											oButton = new sap.m.Button({
												id: oActionjson[k].ACTION,
												text: vBtnText,
												press: onAction
											});
											oDetailPage.addFooterCustomAction(oButton);
											break;
									}
								}
							}
							oViewModel.setProperty("/headjson", oHeadjson);
							oViewModel.setProperty("/itemhjson", oItemhjson);
							oViewModel.setProperty("/itemrjson", oItemrjson);
							oViewModel.setProperty("/attachjson", oAttachjson);

						}.bind(this),
						error: function(oData) {
							oViewModel.setProperty("/headjson", "");
							oViewModel.setProperty("/itemhjson", "");
							oViewModel.setProperty("/itemrjson", "");
							oViewModel.setProperty("/attachjson", "");
							this.showErrorMessage(oData.message);
						}.bind(this)
					});

					//读取request 历史信息
					this.getModel().read("/HistorySet", {
						filters: [oFilter],
						success: function(oData) {
							//多语言支持
							for (var i in oData.results) {
								if (vLanguage.indexOf("zh") !== -1) {
									oData.results[i].Applevel_desc3 = oData.results[i].Applevel_desc1;
								} else if (vLanguage.indexOf("en") !== -1) {
									oData.results[i].Applevel_desc3 = oData.results[i].Applevel_desc2;
								}
							}

							oViewModel.setProperty("/historyjson", oData.results);

							var sendbackJSON = [];
							var sendbackLevel = []; //用于判断不重复添加
							var sendbackObj = null;
							var sendbackObjLast = null;
							var first = "X";

							for (var l in oData.results) {
								if (oData.results[l].Actualprocessed === "X" && oData.results[l].Canceled === "") {
									sendbackObj = oData.results[l];

									if (sendbackLevel.indexOf(sendbackObj.Applevel) < 0) {
										if (first === "X") {
											sendbackObj.Selected = true;
										} else {
											sendbackObj.Selected = false;
										}
										sendbackJSON.push(sendbackObj);
										sendbackLevel.push(sendbackObj.Applevel);
										first = "";
									}

								}
							}
							//撤销 return for resubmit
							sendbackObjLast = Object.assign({}, sendbackObj);
							sendbackObjLast.Applevel_desc3 = this.getResourceBundle().getText("sendbackforReturnText");
							sendbackObjLast.Selected = false;
							sendbackObjLast.Applevel = "RETURN";
							sendbackJSON.push(sendbackObjLast);

							oViewModel.setProperty("/sendbackjson", sendbackJSON);
							//oViewModel.setProperty("/busy", false);
						}.bind(this),

						error: function(oData) {
							oViewModel.setProperty("/historyjson", "");
							oViewModel.setProperty("/sendbackjson", "");
							this.showErrorMessage(oData.message);
						}.bind(this)
					});

				}.bind(this));
			},

			/* =========================================================== */
			/* event handlers                                              */
			/* =========================================================== */
			/**
			 * Updates the item count within the line item table's header
			 * @param {object} oEvent an event containing the total number of items in the list
			 * @private
			 */
			onListUpdateFinished: function(oEvent) {
				var sTitle,
					iTotalItems = oEvent.getParameter("total"),
					oViewModel = this.getModel("detailView");

				// only update the counter if the length is final
				if (this.byId("lineItemsList").getBinding("items").isLengthFinal()) {
					if (iTotalItems) {
						sTitle = this.getResourceBundle().getText("detailLineItemTableHeadingCount", [iTotalItems]);
					} else {
						//Display 'Line Items' instead of 'Line items (0)'
						sTitle = this.getResourceBundle().getText("detailLineItemTableHeading");
					}
					oViewModel.setProperty("/lineItemListTitle", sTitle);
				}
			},

			/**
			 * Binds the view to the object path. Makes sure that detail view displays
			 * a busy indicator while data for the corresponding element binding is loaded.
			 * @function
			 * @param {string} sObjectPath path to the object to be bound to the view.
			 * @private
			 */
			_bindView: function(sObjectPath) {
				// Set busy indicator during view binding
				var oViewModel = this.getModel("detailView");

				// If the view was not bound yet its not busy, only if the binding requests data it is set to busy again
				oViewModel.setProperty("/busy", false);
				this.getView().bindElement({
					path: sObjectPath,
					events: {
						change: this._onBindingChange.bind(this),
						dataRequested: function() {
							oViewModel.setProperty("/busy", true);
						},
						dataReceived: function() {
							oViewModel.setProperty("/busy", false);
						}
					}
				});
			},

			_onBindingChange: function() {
				var oView = this.getView(),
					oElementBinding = oView.getElementBinding();
				// No data for the binding
				if (!oElementBinding.getBoundContext()) {
					this.getRouter().getTargets().display("detailObjectNotFound");
					// if object could not be found, the selection in the inbox list
					// does not make sense anymore.
					this.getOwnerComponent().oListSelector.clearMasterListSelection();
					return;
				}
				var oBindData = oElementBinding.getBoundContext().getObject();
				if (oBindData.Status === 'S') {
					this.getRouter().getTargets().display("detailObjectNotFound");
					this.getOwnerComponent().oListSelector.clearMasterListSelection();
				}
				var sPath = oElementBinding.getPath();
				this.getOwnerComponent().oListSelector.selectAListItem(sPath);

				// var fRequestid = new sap.ui.model.Filter("Requestid", sap.ui.model.FilterOperator.EQ, this.vRequestid);
				// var fFilters = [];
				// fFilters.push(fRequestid);
				// this.getModel().read("/RequestSet", {
				// 	filters: [fFilters],
				// 	success: function(oData) {
				// 		if(oData.length===0){
				// 		this.getRouter().getTargets().display("detailObjectNotFound");	
				// 		}
				// 	}.bind(this),

				// 	error: function(oData) {
				// 		this.getRouter().getTargets().display("detailObjectNotFound");
				// 	}.bind(this)
				// });

			},

			_onMetadataLoaded: function() {
				// Store original busy indicator delay for the detail view
				var iOriginalViewBusyDelay = this.getView().getBusyIndicatorDelay(),
					oViewModel = this.getModel("detailView"),
					oLineItemTable = this.byId("lineItemsList"),
					iOriginalLineItemTableBusyDelay = oLineItemTable.getBusyIndicatorDelay();

				// Make sure busy indicator is displayed immediately when
				// detail view is displayed for the first time
				oViewModel.setProperty("/delay", 0);
				oViewModel.setProperty("/lineItemTableDelay", 0);

				oLineItemTable.attachEventOnce("updateFinished", function() {
					// Restore original busy indicator delay for line item table
					oViewModel.setProperty("/lineItemTableDelay", iOriginalLineItemTableBusyDelay);
				});

				// Binding the view will set it to not busy - so the view is always busy if it is not bound
				oViewModel.setProperty("/busy", true);
				// Restore original busy indicator delay for the detail view
				oViewModel.setProperty("/delay", iOriginalViewBusyDelay);
			},

			/**
			 * Set the full screen mode to false and navigate to inbox page
			 */
			onCloseDetailPress: function() {
				this.getModel("appView").setProperty("/actionButtonsInfo/midColumn/fullScreen", false);
				this.getModel("appView").setProperty("/layout", "OneColumn");
				// No item should be selected on inbox after detail page is closed
				this.getOwnerComponent().oListSelector.clearMasterListSelection();
				this.getRouter().navTo("inbox", {
					Userid: this.getOwnerComponent().getModel("user").getProperty("/Userid")
				});
			},

			/**
			 * Toggle between full and non full screen mode.
			 */
			toggleFullScreen: function() {
				var bFullScreen = this.getModel("appView").getProperty("/actionButtonsInfo/midColumn/fullScreen");
				this.getModel("appView").setProperty("/actionButtonsInfo/midColumn/fullScreen", !bFullScreen);
				if (!bFullScreen) {
					// store current layout and go full screen
					this.getModel("appView").setProperty("/previousLayout", this.getModel("appView").getProperty("/layout"));
					this.getModel("appView").setProperty("/layout", "MidColumnFullScreen");
				} else {
					// reset to previous layout
					this.getModel("appView").setProperty("/layout", this.getModel("appView").getProperty("/previousLayout"));
				}
			},

			/**
			 * Attachment related
			 */
			getAttachmentTitleText: function() {
				var aItems = this.byId("uploadCollection").getItems();
				return this.getResourceBundle().getText("attachmentTitleText") + "(" + aItems.length + ")";
			},

			onFileRenamed: function(oEvent) {
				var sDocumentId = oEvent.getParameter("documentId");
				var sPath = "/AttachSet('" + sDocumentId + "')";
				var sFileName = oEvent.getParameter("item").getFileName();
				var oAttachItem = {
					ATTACHID: sDocumentId,
					FILENAME: sFileName
				};
				this.getModel().update(sPath, oAttachItem, {
					method: "PUT",
					success: function(oData) {
						this._refreshAttachBinding();
					}.bind(this),

					error: function(oData) {
						this.showErrorMessage(oData.message);
					}.bind(this)
				});
			},

			onFileDeleted: function(oEvent) {
				this.deleteItemById(oEvent.getParameter("documentId"));
			},

			deleteItemById: function(sItemToDeleteId) {
				var sPath = "/AttachSet('" + sItemToDeleteId + "')";
				this.getModel().remove(sPath, {
					method: "DELETE",
					success: function(oData) {
						this._refreshAttachBinding();
					}.bind(this),

					error: function(oData) {
						this.showErrorMessage(oData.message);
					}.bind(this)
				});
			},

			onUploadChange: function(oEvent) {
				var oUploadCollection = oEvent.getSource();
				// Header Token
				var oModel = this.getView().getModel();
				oModel.refreshSecurityToken();
				var oHeaders = oModel.oHeaders;
				var sToken = oHeaders['x-csrf-token'];
				var oCustomerHeaderToken = new sap.m.UploadCollectionParameter({
					name: "x-csrf-token",
					value: sToken
				});
				oUploadCollection.addHeaderParameter(oCustomerHeaderToken);
			},

			onFileSizeExceed: function(oEvent) {
				this.showErrorMessage("FileSizeExceed event triggered, max 10MB.");
			},

			onTypeMissmatch: function(oEvent) {
				this.showErrorMessage("TypeMissmatch event triggered");
			},

			onBeforeUploadStarts: function(oEvent) {
				var vApproverid = this.getOwnerComponent().getModel("user").getProperty("/Userid");
				var vValue = oEvent.getParameter("fileName") + "," + this.vRequestid + "," + vApproverid;
				vValue = encodeURIComponent(vValue); //Chinese neeeds encode
				// Header Slug
				var oCustomerHeaderSlug = new UploadCollectionParameter({
					name: "slug",
					value: vValue
				});
				oEvent.getParameters().addHeaderParameter(oCustomerHeaderSlug);
			},

			onUploadComplete: function(oEvent) {
				this._refreshAttachBinding();
				// delay the success message for to notice onChange message
				/*      setTimeout(function() {
				        MessageToast.show("Uploaded file successfully.");
				      }, 4000);*/
			},

			_refreshAttachBinding: function() {
				var aItems = [];
				var fRequestid = new sap.ui.model.Filter("REQUESTID", sap.ui.model.FilterOperator.EQ, this.vRequestid);
				var fFilters = [];
				fFilters.push(fRequestid);
				this.getModel().read("/AttachSet", {
					filters: [fFilters],
					success: function(oData) {
						aItems = oData.results;
						this.getModel("detailView").setProperty("/attachjson", aItems);
						this.byId("attachmentTitle").setText(this.getAttachmentTitleText());
					}.bind(this),

					error: function(oData) {
						this.getModel("detailView").setProperty("/attachjson", "");
						this.showErrorMessage(oData.message);
					}.bind(this)
				});
			},

			onDownloadItem: function() {
				var oUploadCollection = this.byId("uploadCollection");
				var aSelectedItems = oUploadCollection.getSelectedItems();
				if (aSelectedItems) {
					for (var i = 0; i < aSelectedItems.length; i++) {
						oUploadCollection.downloadItem(aSelectedItems[i], true);
					}
				} else {
					MessageToast.show("Select an item to download");
				}

				// var oUploadCollection = this.byId("uploadCollection");
				// var aSelectedItems = oUploadCollection.getSelectedItems();
				// var oItem = null;
				// var vSwiftSAPHost = this.getOwnerComponent().getModel("user").getProperty("/Swiftsaphost");

				// if (!vSwiftSAPHost) {
				//  this.showErrorMessage("Please maintain SWIFTSAP Host paramater in Config!");
				// } else {
				//  for (var i = 0; i < aSelectedItems.length; i++) {
				//    oItem = aSelectedItems[i];
				//    //调用Odata服务
				//    var sObjectPath01 = this.getModel().createKey("/AttachSet", {
				//      ATTACHID: oItem.getDocumentId()
				//    });
				//    sObjectPath01 = vSwiftSAPHost + "/sap/opu/odata/sap/YBC_SWIFTSAP_SRV" + sObjectPath01 + "/$value";
				//    var w = window.open(sObjectPath01, '_blank');
				//    if (w == null) {
				//      this.showErrorMessage("Download file failed, please retry!");
				//    }

				//  }
				// }
			},

			/*  onVersion: function() {
			    var oUploadCollection = this.byId("uploadCollection");
			    var aSelectedItems = oUploadCollection.getSelectedItems();
			    var oItem = null;
			    if (aSelectedItems) {
			      for (var i = 0; i < aSelectedItems.length; i++) {
			        //oUploadCollection.downloadItem(aSelectedItems[i], true);
			        oItem = aSelectedItems[i];
			        //调用Odata服务
			        var sObjectPath01 = this.getModel().createKey("/AttachSet", {
			          ATTACHID: oItem.getDocumentId()
			        });
			        this.getModel().read(sObjectPath01, {
			          success: function(oData) {
			            var base64EncodedPDF = oData.Content; // the encoded string
			            var decodedPdfContent = atob(base64EncodedPDF);
			            //  var decodedPdfContent = decodeURIComponent(escape(atob(base64EncodedPDF)));
			            var byteArray = new Uint8Array(decodedPdfContent.length);
			            for (var j = 0; j < decodedPdfContent.length; j++) {
			              byteArray[j] = decodedPdfContent.charCodeAt(j);
			            }
			            var blob = new Blob([byteArray.buffer], {
			              type: "application/pdf"
			            });
			            var _pdfurl = URL.createObjectURL(blob);

			            if (!this._PDFViewer) {
			              this._PDFViewer = new sap.m.PDFViewer({
			                width: "auto",
			                source: _pdfurl // my blob url
			              });
			              jQuery.sap.addUrlWhitelist("blob"); // register blob url as whitelist
			            }
			            this._PDFViewer.downloadPDF = function() {
			              sap.ui.core.util.File.save(
			                byteArray.buffer,
			                "Hello_UI5",
			                "pdf",
			                "application/pdf"
			              );
			            };
			            this._PDFViewer.open();
			          }.bind(this),
			          error: function(oData) {
			            this.showErrorMessage(oData.message);
			          }.bind(this)
			        });

			      }
			    } else {
			      MessageToast.show("Select an item to download");
			    }
			  },*/

			onSelectionChange: function() {
				var oUploadCollection = this.byId("uploadCollection");
				if (oUploadCollection.getSelectedItems().length > 0) {
					this.byId("downloadButton").setEnabled(true);
				} else {
					this.byId("downloadButton").setEnabled(false);
				}
			},
			onCrossApplicationNavigation: function(semanticObject, sAction, oParams) {
				var oCrossAppNavigator = sap.ushell.Container.getService("CrossApplicationNavigation"); // get a handle on the global XAppNav service
				var hash = (oCrossAppNavigator && oCrossAppNavigator.hrefForExternal({
					target: {
						semanticObject: semanticObject,
						action: sAction
					},
					params: oParams
				})) || ""; // generate the Hash to display a Mapping
				oCrossAppNavigator.toExternal({
					target: {
						shellHash: hash
					}
				}); // navigate to Mapping application
			},
			onPressNumber: function(oEvent) {
				var oBindingData = oEvent.getSource().getBindingContext("detailView").getObject();
				var sSupplier = "";
				if (oBindingData.VALUE) {
					if (oBindingData.VALUE.split("(")[1]) {
						sSupplier = oBindingData.VALUE.split("(")[1].split(")")[0];
					} else {
						sSupplier = oBindingData.VALUE;
					}

				}

				// for(var i in oViewHeaderData){
				// 	if(oViewHeaderData[i].FIELD==="LIFNR"){
				// 		sSupplier = oViewHeaderData[i].VALUE;
				// 		break;
				// 	}
				// }
				switch (oBindingData.FIELD) {
					case "LBLNI":
						this.onCrossApplicationNavigation("Z_MMPURUIML81N", "display", {
							"P_LBLNI": oBindingData.VALUE,
							"sap-ui-tech-hint": "GUI"
						});
						break;
					case "EBELN":
						this.onCrossApplicationNavigation("Z_MMPURPAMEPO", "display", {
							"P_EBELN": oBindingData.VALUE,
							"sap-ui-tech-hint": "GUI"
						});
						//this.onCrossApplicationNavigation("PurchaseOrder","displayFactSheet",{"PurchaseOrder":oBindingData.VALUE});
						break;
					case "LIFNR":
						//this.onCrossApplicationNavigation("Supplier","displayPurchasingDetails",{"I_LIFNR-LOW":sSupplier,"sap-ui-tech-hint":"GUI"});
						this.onCrossApplicationNavigation("Supplier", "displayFactSheet", {
							"Supplier": sSupplier
						});
						break;
					default:
						break;

				}

			}

		});

	});